package cn.ryanpenn.es.spring.dao.impl;

import cn.ryanpenn.es.spring.dao.HelloDao;
import cn.ryanpenn.es.spring.model.Hello;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * HelloDaoImpl
 */
@Repository
public class HelloDaoImpl implements HelloDao {

    private List<Hello> history = new ArrayList<>();
    private int seqId = 0;

    @Override
    public int add(Hello hello) {
        if (!history.contains(hello)) {
            seqId++;
            hello.setId(seqId);
            history.add(hello);
            return hello.getId();
        }
        return -1;
    }

    @Override
    public boolean update(Hello hello) {
        for (Hello item : history) {
            if (item.getId() == hello.getId()) {
                item.setFrom(hello.getFrom());
                item.setTo(hello.getTo());
                item.setMessage(hello.getMessage());
                return true;
            }
        }

        return false;
    }

    @Override
    public boolean delete(int id) {
        return history.removeIf(item -> {
            return item.getId() == id;
        });
    }

    @Override
    public Hello getById(int id) {
        Optional<Hello> ret = history.stream().filter(item -> item.getId() == id).findFirst();

        if (ret.isPresent()) {
            return ret.get();
        }
        return null;
    }

    @Override
    public List<Hello> query(String user) {
        return history.stream()
                .filter(item -> {
                    return item.getFrom().equalsIgnoreCase(user) || item.getTo().equalsIgnoreCase(user);
                }).collect(Collectors.toList());
    }
}
